﻿using System.Collections.Generic;
using System.Linq;
using System.Xml;

namespace etp
{
    internal class Question
    {
        public string Text { get; set; }
        public QuestionType Type { get; set; }

        public List<Answer> Answers { get; private set; }

        public Question()
        {
            Answers = new List<Answer>();
        }

        public static Question FromXml(XmlNode node)
        {
            var rawOptions = node.SelectSingleNode("options").InnerText
                .Split('\n')
                .Select(t => t.TrimStart().TrimEnd().Split('='))
                .Where(t => t.Length != 1)
                .ToDictionary(k => k[0], e =>
                                         {
                                             int i;
                                             return int.TryParse(e[1], out i) ? i : 0;
                                         });

            var right = rawOptions["right"];
            var type = (QuestionType) rawOptions["type"];

            return new Question
                   {
                       Text = node.SelectSingleNode("question").InnerText.TrimEnd().TrimStart(),
                       Type = type,
                       Answers = Enumerable.Range(1, rawOptions["n"])
                           .Select(n => new Answer
                                        {
                                            Text = node.SelectSingleNode("a_" + n).InnerXml
                                                .TrimStart().TrimEnd(),

                                            Correct = (type == QuestionType.SelectFew && n <= right)
                                                      || (type == QuestionType.SelectOne && n == right)
                                                      || type == QuestionType.Match
                                                      || type == QuestionType.TextAnswer

                                        }).ToList()
                   };
        }
    }
}